# Contributor: Matthias Ahouansou <matthias@ahouansou.cz>
# Contributor: fossdd <fossdd@pwned.life>
# Maintainer: Matthias Ahouansou <matthias@ahouansou.cz>
pkgname=mautrix-signal
pkgver=0.7.2
_libsignalver=0.58.3
pkgrel=0
pkgdesc="A Matrix-Signal puppeting bridge"
url="https://go.mau.fi/mautrix-signal/"
arch="all !armhf !armv7 !x86 !ppc64le !s390x !loongarch64" # boring ssl only supports 64 bit, and doesn't set OPENSSL_64_BIT for ppc64le, s390x, loongarch64
license="AGPL-3.0-or-later"
# clang18 because of https://github.com/signalapp/boring/issues/28, should be fixed once libsignal updates the boring crate
makedepends="
	cargo
	cargo-auditable
	clang18-libclang
	cmake
	go
	olm-dev
	protoc
	sqlite-dev
"
install="$pkgname.pre-install $pkgname.post-upgrade"
subpackages="$pkgname-openrc $pkgname-doc"
source="
	signal-$pkgver.tar.gz::https://github.com/mautrix/signal/archive/refs/tags/v$pkgver.tar.gz
	libsignal-$_libsignalver.tar.gz::https://github.com/signalapp/libsignal/archive/refs/tags/v$_libsignalver.tar.gz
	mautrix-signal.initd
	mautrix-signal.confd
"
builddir="$srcdir/signal-$pkgver"
options="net"
_rust_dir=pkg/libsignalgo/libsignal

export GOFLAGS="$GOFLAGS -tags=libsqlite3"
export GOCACHE="${GOCACHE:-"$srcdir/go-cache"}"
export GOTMPDIR="${GOTMPDIR:-"$srcdir"}"
export GOMODCACHE="${GOMODCACHE:-"$srcdir/go"}"

prepare() {
	default_prepare
	mv -T "$srcdir/libsignal-$_libsignalver" "$_rust_dir"
	cd "$_rust_dir"
	cargo fetch --target="$CTARGET" --locked
}

build() {
	export CGO_CFLAGS="$CFLAGS"
	export CGO_LDFLAGS="$LDFLAGS"

	cd "$_rust_dir"
	cargo auditable build -p libsignal-ffi --release --frozen
	mv target/release/libsignal_ffi.a "$builddir"

	cd "$builddir"
	LIBRARY_PATH=. go build \
		-ldflags "-X main.Tag=$pkgver -X 'main.BuildTime=$(date -d @"$SOURCE_DATE_EPOCH" '+%b %_d %Y, %H:%M:%S')'" \
		./cmd/mautrix-signal

	./mautrix-signal -e
}

check() {
	LIBRARY_PATH=. go test ./...
}

package() {
	install -Dm755 mautrix-signal \
		-t "$pkgdir"/usr/bin/
	install -Dm644 config.yaml \
		-t "$pkgdir"/etc/mautrix-signal/

	install -Dm755 "$srcdir"/mautrix-signal.initd \
		"$pkgdir"/etc/init.d/mautrix-signal
	install -Dm644 "$srcdir"/mautrix-signal.confd \
		"$pkgdir"/etc/conf.d/mautrix-signal

	install -Dm 644 LICENSE "$pkgdir"/usr/share/licenses/"$pkgname"/LICENSE
}

sha512sums="
ee43a97c06de307bca859227eb61f67de879a9e1d6b4926a2af48bbba24811900541ea777ca59876f31bf482a81c94e320794d2f3bd58e92d855c142e0046846  signal-0.7.2.tar.gz
6d99f5f67b3795b468577763edbeb965f4e53f021c0caf17b2c7dc262777784508d77c772822189c920263f927503a40733f8c1b51ce93343d872c4c9ef5bb4b  libsignal-0.58.3.tar.gz
6a4878bd732db4442418b1cedbecd901cb9633846943cf98ebfe09aafa9da341168be7bafdb0a88015f0bbcafd665295364797efcd2d88855301341b996415b0  mautrix-signal.initd
ffcfed000e4ca779a055ddf4374753e23e424501a70a148e9785a4c4f6f2d32e94e2275a766ac9435b2509a1d621821a2baad8c5e4964ef08cbd13045cb430df  mautrix-signal.confd
"
